<?php

class OrderController extends MemberBaseController
{
	public $layout = '//layouts/main_mini';
    public $pageKeyword = '';
    public $pageDesc    = '';


    //购物车结算
	public function actionConfirm_order()
	{
        $this->pageTitle   = t('Cart','cart');
		$cart = Yii::app()->cart;
        $mycart = $cart->com_contents(); //取购物车信息        
        
        //print_r($mycart);
        //如果购物车为空
        if(empty($mycart)){
            Message(t('Cart Empty')); 
            exit;
        }
        $companyids = array(); //定义公司ID集
        //取购物车内产品的所有公司
        $companyids = $cart->company();
        
        //取购物计算运费用的数据
        $pro_postageids = $cart->total_postage_pro();
       	
       	//取购物车里的运费模板
        $postage = $cart->total_postage();

        //判断客户选择的运送方式
        if(isset($_POST['exptype']))
        {
            $zel_type = $_POST['exptype'];
            $expid = $_POST['expid'];           
            //写快递选择进COOKIE
            $cookie = new CHttpCookie('zel_type'.$expid,$zel_type);
            $cookie->expire = time()+60*60*24; 
            Yii::app()->request->cookies['zel_type']=$cookie;
            //写快递模板选择进COOKIE
            $cookie = new CHttpCookie('expid'.$expid,$expid);
            $cookie->expire = time()+60*60*24; 
            Yii::app()->request->cookies['expid'.$expid]=$cookie;
            
        }

        if(isset($_POST['addid']))
        {
            //写地址选择进COOKIE
            $cookie = new CHttpCookie('addid',$_POST['addid']);
            $cookie->expire = time()+60*60*24; 
            Yii::app()->request->cookies['addid'] = $cookie; 
        }

        //取默认的计算方式        
        foreach ($postage as $key => $val) {        	      	    	
        	$explog = ExpressLog::model()->findByAttributes( array('ze_id'=>$val,'zel_default'=>'2'),array('order'=>'zel_type ASC'));        	
        	//判断是否有选择的运费方式.有代入计算,无则取默认的
            $cookie = Yii::app()->request->getCookies();          
            if($cookie['expid'.$val]->value == $val ){
                $stype[$val] = $cookie['zel_type'.$val]->value;
            }else{
                $stype[$val] = $explog->zel_type;
            }
            
        } 

        
        //取选择的地址ID
        $cookie = Yii::app()->request->getCookies();
        $addid = $cookie['addid']->value;

        //选择的地址信息
        if(!empty($addid)){
            $address = MemAddres::model()->getMemAddressInfo($addid);
        }else{
            //取默认的地址
            $adds = MemAddres::model()->findByAttributes(array('zm_id'=>user()->userid,'zma_default'=>1));
            $address = MemAddres::model()->getMemAddressInfo($adds->zma_id);
        }        
        //取当前区域ID
        if($address['param']['zar_id'] == ''){
        	$memaddres = MemAddres::model()->findByAttributes(array('zm_id'=>user()->userid,'zma_default'=>1)); 
        	$ze_id = $memaddres->zar_id;
        }else{
        	$ze_id = $address['param']['zar_id'];
        }
        //取地址二级ID
		$area = Area::model()->findByPk($ze_id);
        //计算总运费
     
        $expprice = ExpressLog::model()->getexpprice($pro_postageids,$area->zar_parentid,$stype);
        //商品实付价格
        $real_price = $cart->total();        
         //是否有活动产品
        $activity_pro = $cart->activity_pro();
        //当有活动产品时
        if($activity_pro == 1){
            //充许多重优惠
            if(F::setting('Multiplediscount') ==1){
            //满就送金额 
                $Fullsent = CmpPromotion::model()->getFullsent($real_price);
            }else{
                $Fullsent = 0;
            }
        }else{
            $Fullsent = CmpPromotion::model()->getFullsent($real_price); //
        }

        //订单总价            
        $total = $real_price+$expprice;  //商品价格-活动价+运费

        //运费类型,1为免邮,2为模板
		$exptype = array('0'=>'1','1'=>'2');		
		$this->render('confirm_order', array(
            'mycart'     => $mycart,         //购物车信息
            'companyids' => $companyids,     //公司ID集
            'exptype'    => $exptype,        //运送方式
            'addid'      => $addid,          //选择的地址ID
            'address'    => $address,        //选择的地址信息
            'activity_pro'=> $activity_pro,  //是否有活动产品
            'fullsent'   => $Fullsent,      //满就送
            'expprice'   => $expprice,       //运费总价         
            'total'      => $total           //订单总价
        ));        
	}
    /*
     * 新增收货地址
     */
    public function actionSaveAddress()
    {
         $model=new MemAddres();
         if(isset($_POST['MemAddres']))
         {
             $address              = $_POST['MemAddres'];
             //print_r($address);
             $address['zm_id']     = user()->userid;
             $addnum = count($model->findall('zm_id='.user()->userid));
             
             //如果有地址不设为默认,如果无即设为默认
             if($addnum >= 1){
                $address['zma_default_sent'] = 0;  
                $address['zma_default'] = 0;
             }else{
                $address['zma_default_sent'] = 1;  
                $address['zma_default'] = 1;
             }
             //print_r($address);exit;               
             $model->attributes = $address;
             if(empty($model->zar_id))
                    $model->zar_id = $_POST['city_id'];
             if($model->validate())//这里是先验证数据，如果通过再save()。  
            {
                //print_r($model->zma_name);exit;
                $model->save();
                $cookie = new CHttpCookie('addid',$model->zma_id);  
                $cookie->expire = time()+60*60*24*1;  //有限期1天
                Yii::app()->request->cookies['addid']=$cookie; 
                header301("/member/order/confirm_order");
            }else{
               $this->render('../index/error',array('message'=>'写入会员地址出错!',
                        'links'=>array(                       
                            array('查看结算','/member/order/confirm_order'),                                                
                        )
                        ));  
                exit;
            }
        }

         
    }
    /*
     * 确认订单 
     */
    public function actionSaveOrder()
    {
        //print_r(Yii::app()->user->userid);
        $this->pageTitle   = t('Cart','cart');
        $order              = $_POST['order'];
        $cart               = Yii::app()->cart;       
        $mycart             = $cart->contents();                       //取购物车信息
        $time               = time();                                 
        $order['zm_id']     = Yii::app()->user->userid;
        //如果购物车为空
        if(empty($mycart)){
            Message(t('Cart Empty'));
            exit;
        }
        //取购物车内产品的所有公司
        $companyids = $cart->company();
        //print_r($companyids);exit;
        $order['zm_id_cmp'] = implode(',', $companyids);               //商家ID
        $order['zo_id']     = $time.random('1');                       //生成订单号
        $order['zo_status'] = 1;                                       //确认订单状态
        
        //查询选择的地址信息
        $address = MemAddres::model()->getMemAddressInfo($order['address']);
        unset($order['address']);
        //将地址信息写入订单
        $order['zo_name'] = $address['param']['zma_name'];              //联系人
        if( $address['param']['zma_tel'] !='' ){
            $order['zo_telphone']   = $address['param']['zma_tel'];
        }else{
             $order['zo_telphone']  = $address['param']['zma_mob'];     //联系电话
        }
        $order['zar_id']            = $address['param']['zar_id'];      //省市ID
        $order['zo_zip']            = $address['param']['zma_zip'];     //邮编
        $order['zo_address']        = $address['address'];              //地址
        $order['zo_mobile']         = $address['param']['zma_mob'];     //手机
        $order['zo_email']          = $address['param']['zma_email'];   //Email
        $order['zo_payable_amount'] = $cart->total();                   //应付商品总金额
        $order['zo_create_time']    = $time;                            //下单时间

        //取购物计算运费用的数据
        $pro_postageids = $cart->total_postage_pro();
        //取购物车里的运费模板
        $postage = $cart->total_postage();        
        //取默认的计算方式
        foreach ($postage as $key => $val) {        	      	    	
        	$explog = ExpressLog::model()->findByAttributes( array('ze_id'=>$val),array('order'=>'zel_type ASC'));        	
        	//判断是否有选择的运费方式.有代入计算,无则取默认的
            $cookie = Yii::app()->request->getCookies();          
            if($cookie['expid'.$val]->value == $val ){
                $stype[$val] = $cookie['zel_type'.$val]->value;
            }else{
                $stype[$val] = $explog->zel_type;
            }            
        } 

         //取地址二级ID
        $area = Area::model()->findByPk($order['zar_id']);
        //计算总运费
        $expprice = ExpressLog::model()->getexpprice($pro_postageids,$area->zar_parentid,$stype); 

        if( $expprice != 0 ){
            $order['zo_real_freight'] = $expprice; //实付快递费用
        }
        
        //是否有活动产品
        $activity_pro = $cart->activity_pro();
         
        //商品实付价格
        $real_price = $cart->total(); 

        //当有活动产品时
        if($activity_pro == 1){
            //充许多重优惠
            if(F::setting('Multiplediscount') ==1){
                //满就送金额 
                $Fullsent = CmpPromotion::model()->getFullsent($real_price);
            }else{
                $Fullsent = 0;
            }
        }else{
            $Fullsent = CmpPromotion::model()->getFullsent($real_price); //
        }

        if($order['favorable']==1){
            //计算使用优惠后金额
            if($order['ticket']!=''){
                $memticket =  MemTicket::model()->find('zmi_id=:ticketid And zm_id =:zm_id',array(':ticketid'=>$order['ticket'],':zm_id'=>Yii::app()->user->getId()));
                $order['zo_amount']       = $cart->total()-$memticket->zmi_val+$expprice;       //应付商品总金额(使用优惠券后)
            }else{
                $order['zo_amount']       = $cart->total()+$expprice; //总价
            }
        }elseif($order['favorable']==2){
            //计算使用满就送后金额                        
            $order['zo_amount']       = $cart->total()-$Fullsent+$expprice;       //应付商品总金额(使用满就送后)
           
        }else{
            $order['zo_amount']       = $cart->total()+$expprice; //总价
        }
               
        //判断积分方式
        if(F::setting('pointsys')==1){
            $order['zo_point']        = floor($cart->total()/F::setting('points'));//增加积分
        }else{
             foreach ($mycart as $key => $value) {
                $order['zo_point']   += $value['point']*$value['qty'];     //产品总积分
             }
        }        
        $order['zo_consumption']  = 0; //消费积分

        //积分模型数据
        $point                   = array();
        $point['zm_id']          = $order['zm_id'];
        $point['zpl_action']     = '1';
        $point['zpl_ip']         = Yii::app()->request->userHostAddress;  
        $point['zo_id']          = $order['zo_id'];
        $point['inputtime']      = $time;

        //print_r($order);exit;
        $modelA = new Order;//实例化订单模型 
        
       
		$modelA->attributes = $order;
		//写入订单数据
		if($modelA->validate())//这里是先验证数据，如果通过再save()。  
        {   
            //写入增加积分记录
            if( $order['zo_point'] != 0 ){
                $point['zpl_type']   = '1';
                $point['zpl_points'] = $order['zo_point'];
                $modelC              = new PointLog;//实例化积分模型                
                $modelC->attributes  = $point;
                if($modelC->validate())//这里是先验证数据，如果通过再save()。  
                {   
                        $modelC->save();
                } 
            }
            //写入扣除积分记录
            if( $order['zo_consumption'] != 0 ){
                $modelD              = new PointLog;//实例化积分模型
                $point['zpl_type']   = '2';
                $point['zpl_points'] =  $order['zo_consumption'];
                $modelD->attributes  = $point;
                if($modelD->validate())//这里是先验证数据，如果通过再save()。  
                {   
                        $modelD->save();
                }               
            }
            
            //写入发票记录
            if( $order['zo_id'] != 0 ){
                $modelI              = new OrdInvoice;//实例化积分模型
                $invoice['zo_id']   = $order['zo_id'];
                $invoice['zol_type'] =  1; //默认为普通发票
                $invoice['zol_status'] =  1;
                $modelI->attributes  = $invoice;
                if($modelI->validate())//这里是先验证数据，如果通过再save()。
                {
                        $modelI->save();
                }
            }

            //添加优惠券使用记录
            if( $order['ticket']!='' ){                
                $ticketlog            = new TicketLog();
                $ticketlog->zm_id     = $order['zm_id'];
                $ticketlog->zti_id    = $memticket->zti_id;
                $ticketlog->ztl_type  = 2;
                $ticketlog->ztl_num   = 1;
                $ticketlog->ztl_price = $memticket->zmi_val;
                $ticketlog->inputtime = $time;
                $ticketlog->zo_id     = $order['zo_id'];
                $ticketlog->save();
                //更新会员优惠券状态
                if( $memticket->zmi_num > 1 )
                {
                    $memticket->zmi_num    = $memticket->zmi_num-1; 

                }else{
                    $memticket->zmi_num    = $memticket->zmi_num-1;
                    $memticket->zmi_status = 2;                   
                }
                //print_r($memticket);
                $memticket->save(); 
                

                //写入订单优惠信息表
                $discount = new OrdDiscount;//实例化订单优惠模型
                $discount->zo_id = $order['zo_id'];
                $discount->zti_id = $memticket->zti_id;
                $discount->zod_price = $memticket->zmi_val;
                $discount->zod_type = 4;
                 $discount->zp_id = 0;
                $discount->save();
            }
            //写入满就送优惠信息
            if($order['favorable']==2){
                $discount = new OrdDiscount;//实例化订单优惠模型
                $discount->zo_id = $order['zo_id'];                
                $discount->zod_price = $Fullsent;
                $discount->zod_type = 6;
                $discount->zp_id = 0;
                $discount->save();
            }            
     		if($modelA->save(false)){
     			//写入订单产品数据
		        $ordproduct =array();		        
		        foreach ($mycart as $key => $value) {
		        	$ordproduct[$key]['zo_id']          = $order['zo_id'];                   //订单ID
                    $ordproduct[$key]['zm_id_mem']      = $order['zm_id'];                   //消费会员ID     
		        	$ordproduct[$key]['zm_id']          = $value['zm_id'];                   //商品会员ID
		        	$ordproduct[$key]['zp_id']          = $value['id'];                      //产品ID
		        	$ordproduct[$key]['zop_title']      = $value['title'];                   //产品标题
		        	$ordproduct[$key]['zop_nums']       = $value['qty'];                     //产品数量
		        	$ordproduct[$key]['zop_price']      = $value['saleprice'];               //商品价格
                    $ordproduct[$key]['zop_real_price'] = $value['price'];                   //实付价格
		        	$ordproduct[$key]['zop_weight']     = $value['weight'];                  //产品重量
                    if(F::setting('pointsys')==1){
                        $ordproduct[$key]['zop_set_point']  = floor($value['price']/F::setting('points'));     //产品积分
                    }else{
                        $ordproduct[$key]['zop_set_point']  = $value['point']*$value['qty'];     //产品积分
                    }
		        	$ordproduct[$key]['zop_spe']        = serialize($value['options']);      //序列化产品规格
		        	$ordproduct[$key]['zpa_pro_no']     = $value['no'];                      //产品编号
		        	$ordproduct[$key]['zop_pic']        = $value['pic_url'];                 //产品图片地址
                    $ordproduct[$key]['zop_meal']       = !empty($value['package'])?2:1;     //是否套餐

                    
                    //产品优惠信息
                    $orddiscount[$key]['zo_id']         = $order['zo_id'];
                    $orddiscount[$key]['zp_id']         = $value['id'];
                    $orddiscount[$key]['zod_price']     = ($value['saleprice']*$value['qty'])-($value['price']*$value['qty']);
                    $orddiscount[$key]['zod_type']      = $value['active'];

		        	$modelB                             = new OrdProduct;//实例化订单产品模型  
		        	$modelB->attributes                 = $ordproduct[$key]; 
		        	if($modelB->validate())//这里是先验证数据，如果通过再save()。  
		         	{   
		         		$modelB->save();
		         	}
                    //取订单产品ID
                    $orddiscount[$key]['zop_id'] = $modelB->attributes['zop_id'];
                    $modelD                             = new OrdDiscount;//实例化订单优惠模型  
                    $modelD->attributes                 = $orddiscount[$key];
                    if($modelD->validate())//这里是先验证数据，如果通过再save()。  
                    {   
                        $modelD->save();
                    }
                    //更新产品库存
                    $product = Product::model()->findByPk($value['id']);
                    $product->zp_inventory = $product->zp_inventory - $value['qty'];//扣库存
                    $product->zp_sale_num  = $product->zp_sale_num+$value['qty']; //增加销量
                    $product->save();
                    
		        }
	        } 
            //给商家发送下单信息
            foreach ($companyids as $comkey => $comval) {
                OrdMsg::model()->setOrdMsg($comval,$order['zo_id'],1);
            }
            

            //成功跳转到支付页
            $id = $modelA->attributes['zo_id'];            
	        header301('/member/order/PayOrder/orderid/'.$id);
	         //删除购物车
            $cart->destroy();        	      
        }else{
            //错误跳转回结算页
        	header301('/member/order/confirm_order');
        }  
        
        //print_r($order);exit;       

    }

    /*
     * 确认订单 
     */
    public function actionPayOrder()
    {
        //订单ID
        $orderid              = $_GET['orderid']; 
        //决断是否有ID
        if(!empty($orderid)){
            $order          = Order::model()->find('zo_id=:orderid AND zm_id=:zm_id',array(':orderid'=>$orderid,':zm_id'=>Yii::app()->user->userid));
            $product            = OrdProduct::model()->find('zo_id=:orderid',array(':orderid'=>$orderid));
            Yii::app()->cart->destroy();      //删除购物车信息                
           // print_r($product);
            $this->render('payorder', array(
                    'product'    => $product,         //产品信息
                    'order'      => $order          //订单总价
            ));
        }else{
            header301('/member/index/');
        }
        
    }

    /*
     * 根据支付方式不同进行支付
     * 
     */
    public function actionPayment()
    {
        $orderid            = $_GET['orderid']; 
        $payid              = $_GET['payid']; 
        //查询支付方式
        $payment = Payment::model()->findByPk($payid);
        //print_r($_GET);
        if(!empty($orderid)){
            $order          = Order::model()->find('zo_id='.$orderid);            
            $product        = $order->orderProduct['0']->attributes;
            //判断订单是否存在
            if(empty($order)){
            	Message(t('No Order'));
            	exit();
            }
            //判断支付状态
            if($order->zo_pay_status != 1){
            	 header301('/member/index/vieworder/orderid/'.$orderid);
            }
            //判断是否线上支付
            if( $payment->zpy_online == 2 ){
                //print_r($payment->class_name);exit;
                if($payment->class_name == 'AlipayDirect'){
                    $params = array(
                    "out_trade_no"  => $orderid,//商户订单号
                    "subject"   => $product['zop_title'],//订单名称
                    "total_fee" => $order->zo_amount,//付款金额                    
                    "body"  => $order->zo_postscript, //订单描述
                    "show_url"  => Yii::app()->homeUrl.'/member/index/orders',//商品展示地址                 
                    //"anti_phishing_key" => time(),//防钓鱼时间戳
                    //"exter_invoke_ip"   => Yii::app()->request->userHostAddress,//客户端的IP地址
                    );
                }elseif ($payment->class_name == 'AlipayEscow'){
                    $params = array(
                    "out_trade_no"  => $orderid,//商户订单号
                    "subject"   => $product['zop_title'],//订单名称
                    "price" => $order->zo_amount,//付款金额
                    "quantity"  => '1',//商品数量
                    "logistics_fee" => '0',//物流费用
                    "logistics_type"    => 'EXPRESS',//物流类型，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
                    "logistics_payment" => 'SELLER_PAY',//物流支付方式SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
                    "body"  => $order->zo_postscript, //订单描述
                    "show_url"  => Yii::app()->homeUrl.'/member/index/orders',//商品展示地址
                    "receive_name"  => $order->zo_name,//收货人姓名
                    "receive_address" => $order->zo_address,//收货人地址
                    "receive_zip"   => $order->zo_zip, //收货人邮编
                    "receive_phone" => $order->zo_telphone,//收货人电话号码
                    "receive_mobile"    => $order->zo_mobile,//收货人手机号码
                    );
                }else{
                     $this->render('../index/error',array('message'=>'没有此支付方式!')  
                    );  
                    exit;
                }            
	            
	            //更新支付方式
	            $this->updateOrderStatus($orderid,$payid);           
            	Payment::model()->pay($params,$payid);
            }else{
            	//线下支付状态更新
            	$this->updateOrderStatus($orderid,$payid,null,'5');
            	$this->render('payment', array(
                    'product'     => $product,         //产品信息
                    'order'      => $order,          //订单总价
                    'payment'   => $payment
            	));
            }      
         }else{
            header301('/member/index/');
        }
    }

    /*
     * 确认订单
     * 
     */
    public function actionConfirmOrder()
    {
        $orderid        = !empty($_GET['orderid'])?$_GET['orderid']:''; 
        if($_POST['pay_ok']=='ok'){
                $member      = Member::model()->findByPk(Yii::app()->user->userid);
                //加密密码
               // $paypassword = $member->passwordEncode($_POST['password'],2);
                //判断密码
                $paypwd      = $member->checkPassword($_POST['password'],2); 
                //print_r($paypwd);exit;               
                if($paypwd == ''){
                    setFlash(t('PayPassword Error'));                                        
                }else{
                    $this->updateOrderStatus($orderid,null,3,null,5);                                 
                    header301('/member/order/okorder/orderid/'.$orderid); 
                }
        }
        $order          = Order::model()->find('zo_id=:orderid AND zm_id=:zm_id',array(':orderid'=>$orderid,':zm_id'=>Yii::app()->user->userid));
        //print_r($order->attributes['zo_id']);exit();
        $product        = $order->orderProduct;
        //print_r($product);exit();
              
        $this->render('confirmorder', array(
                    'product'     => $product,         //产品信息
                    'order'      => $order,          //订单
                   
                ));
    }

    public function actionOkOrder()
    {  
         $this->render('okorder');
    }

    /*
     * 更新订单状态
     * @param $order_id 订单ID
     * @param $payid 支付方式
     * @param $status 订单状态
     * @param $paystatus 支付状态
     * @param $expstatus 物流状态
     */
    public function updateOrderStatus( $orderid,$payid=null,$status=null,$paystatus=null,$expstatus=null)
    {
    	$model=$this->loadModel($orderid);
    	// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$order['zo_id'] = $orderid ;
        if($payid!=null){
		$order['zpy_id'] = $payid;
        }
		if($status!=null){
		    $order['zo_status'] = $status;
            //订单完成时间
            if($status == 3){
                $order['zo_voer_time'] = time();
            }
        
		}
		if($paystatus!=null){
		  $order['zo_pay_status'] = $paystatus;
          //支付时间
          if($paystatus == 2){
            $order['zo_pay_time'] = time();
          }
         
		}
		if($expstatus!=null){
		    $order['zo_exp_status'] = $expstatus;
            //发货时间
            if($expstatus == 2){
                $order['zo_send_time'] = time();
            }
            //收货时间
            if($expstatus == 5){
                $order['zo_accept_time'] = time();
                $order['zo_accept_type'] = 1;
            }
		}
        //print_r($order);exit;
		if(isset($order))
		{
			$model->attributes = $order;
			if($model->save())
				return true;
		}
    }

    /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Order::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}